import {Component, OnInit, ViewChild} from '@angular/core';
import {UserTableComponent} from "../../shared/component/user-table/user-table.component";
import {FormBuilder, FormGroup} from "@angular/forms";
import {ActivatedRoute} from "@angular/router";
import {Http} from "@angular/http";
import {SingleOpenWinService} from "../../shared/service/single-open-win.service";
import {DriverService} from "../../shared/service/driver.service";
import {FileUploadComponent} from "../../shared/component/file-upload/file-upload.component";
declare var $:any;

@Component({
  selector: 'app-driver-add-form',
  templateUrl: './driver-add-form.component.html',
  styleUrls: ['./driver-add-form.component.css']
})
export class DriverAddFormComponent implements OnInit {

  radioValue:number;
  driverForm:FormGroup;
  @ViewChild(UserTableComponent) userTable :UserTableComponent;
  @ViewChild(FileUploadComponent) child :FileUploadComponent;
  userId:string = this.routeInfo.snapshot.queryParams ["userId"];
  _date = null;
  IDValidFlag:boolean = false;
  licenseTypes:any=[{
    "id":"A1",
    "name":"A1"
  },{
    "id":"A2",
    "name":"A2"
  },{
    "id":"A3",
    "name":"A3"
  },{
    "id":"B1",
    "name":"B1"
  },{
    "id":"B2",
    "name":"B2"
  },{
    "id":"C1",
    "name":"C1"
  },{
    "id":"C2",
    "name":"C2"
  },{
    "id":"C3",
    "name":"C3"
  },{
    "id":"C4",
    "name":"C4"
  },{
    "id":"D",
    "name":"D"
  },{
    "id":"E",
    "name":"E"
  },{
    "id":"F",
    "name":"F"
  },{
    "id":"M",
    "name":"M"
  },{
    "id":"N",
    "name":"N"
  },{
    "id":"P",
    "name":"P"
  }];


  constructor(
    private routeInfo:ActivatedRoute,
    private fb:FormBuilder,
    private http:Http,
    private singleOpenWinService:SingleOpenWinService,
    private driverService:DriverService
  ) {

  }

  ngOnInit() {

    this.createForm();

    //初始化出生年月
    $('#birthdays').datetimepicker({
      format: 'YYYY-MM-DD',
      locale: 'zh-cn',
      ignoreReadonly: true,
    });

    //初始化领证日期
    $('#certificationDates').datetimepicker({
      format: 'YYYY-MM-DD',
      locale: 'zh-cn',
      ignoreReadonly: true,
    });

    //订阅司机开窗
    this.singleOpenWinService.valueChange.subscribe((info:string)=>{
      console.log("add");
      $('#id').val(this.userTable.selected.id);
      $('#name').val(this.userTable.selected.name);
      this.driverForm.patchValue({
        id:this.userTable.selected.id,
        name:this.userTable.selected.name
      });
      this.userIsVisible = false;
      this.toSearchId("openwin");
    });
  }

  createForm(){
    this.driverForm =this.fb.group({
      oid:'',
      id: '',
      name: '',
      birthday: '',
      gender: '',
      phone: '',
      licenseType: '',
      certificationDate: '',
      creator:this.userId
    });
    // this.radioValue =1;
    console.log(this.userTable);
  }

  toSearchId(str){
    let pid = this.driverForm.get('id').value.replace(/^\s+|\s+$/g,"");
    if(pid.length!=0){
      this.driverService.checkDriverByID(pid)
        .then(res => {
          if(res.code===1){
            alert("司机代号已存在，请重新输入！");
            if(str!="openwin") {
              this.driverForm.patchValue({
                id: '',
              });
            }else{
              this.driverForm.patchValue({
                id: '',
                name: '',
              });
            }
            this.IDValidFlag = false;
          }else{
            this.IDValidFlag = true;
          }
        });
    }
  }

  /**
   *  单选人员开窗
   */
  userIsVisible = false;

  userShowModal = () => {
    this.userIsVisible = true;
  }

  userHandleCancel = (e) => {
    this.userIsVisible = false;
  }

  //司机信息开窗
  driverOpenWin(){
    this.userShowModal();
  }

  //提交表单
  onSubmit(val:any){
    if(this.checkFormData()){
      this.driverForm.patchValue({
        birthday:$('#birthday').val(),
        certificationDate:$('#certificationDate').val()
      });
      this.driverService.createDriver(this.driverForm.value,this.child.fileoids).then(res=>{
        if(res.code ===1){
          alert(res.message);
          this.driverService.listFreshEvent.emit("add");
          this.driverService.searchFreshEvent.emit("add");
          this.driverForm.reset();
          //清空附件列表信息
          this.child.fileList = [];
        }else{
          alert(res.message);
        }
      });
    }
  }

  //验证表单
  checkFormData(){
    //ID重复则不进行下面的判断
    if(!this.IDValidFlag&&this.driverForm.get("id").value){
      return false;
    }else {
      let msg = "";
      let regexp = /^0\d{2,3}-[1-9]\d{6,7}$|^[1][3,4,5,7,8][0-9]{9}$/;  //判断为电话号码
      if (!this.driverForm.get("id").value.replace(/^\s+|\s+$/g,"")) {
        msg += ("请输入司机代号\n");
      }
      if (!this.driverForm.get("name").value.replace(/^\s+|\s+$/g,"")) {
        msg += ("请输入司机名称\n");
      }
      if (typeof(this.driverForm.get("gender").value) == "undefined") {
        msg += ("请选择司机性别\n");
      }
      if (!this.driverForm.get("phone").value.replace(/^\s+|\s+$/g,"")) {
        msg += ("请输入电话号码\n");
      }
      if (this.driverForm.get("phone").value && !regexp.test(this.driverForm.get("phone").value)) {
        msg += ("请输入有效的电话号码\n");
      }
      if (!this.driverForm.get("licenseType").value) {
        msg += ("请选择准驾车型\n");
      }
      if (msg) {
        alert(msg);
        return false;
      } else {
        return true;
      }
    }
  }
}
